import asyncio
import logging
import traceback

logger = logging.getLogger()
is_run = False


async def run_subprocess(command, logger=logger):
    global is_run
    process = None
    try:
        process = await asyncio.create_subprocess_exec(*command, stdout=asyncio.subprocess.PIPE,
                                                       stderr=asyncio.subprocess.PIPE)
        async for line in process.stdout:
            line = line.decode()
            logger.info(line)
    except Exception as e:
        logger.error(f"定时任务spark运行错误:{repr(e)}" + traceback.format_exc())
        raise Exception(f"定时任务spark运行错误:{repr(e)}" + traceback.format_exc())
    finally:
        if process:
            stdout, stderr = await process.communicate()
            if stdout.decode():
                msg = f"定时任务spark stdout: {stdout.decode()}"
                logger.info(msg)
            if stderr.decode():
                msg = f"定时任务spark stderr: {stderr.decode()}"
                logger.error(msg)
            await process.wait()
        is_run = False

# command = ["ping", "-n", "2", "www.baidu.com"]
# # asyncio.run(run_subprocess(command))

# windows 下需要 ProactorEventLoop 使用 create_subprocess_exec 官方说法
# loop = asyncio.ProactorEventLoop()
# asyncio.set_event_loop(loop)
# loop.run_until_complete(run_subprocess(command))
